/*
 * Project Name demo
 * File Name SpringContextHolder
 * Package Name com.huxiaosu.demo.socketio.util
 * Create Time 2023/2/1
 * Create by name：liujie
 */
package com.huxiaosu.demo.socketio.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * Description
 *
 * @ClassName: SpringContextHolder
 * @author: liujie
 * @date: 2023/2/1 13:42
 */
@Slf4j
@Component
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext appContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.appContext = applicationContext;
    }
    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return appContext.getBean(name);

    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return appContext.getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return appContext.getBean(name, clazz);
    }

    /**
     *
     *  发送事件
     *
     * @param event 事件
     * @author liujie
     * @date 2021/7/15 14:42
     */
    public static void publishEvent(ApplicationEvent event) {
        if (appContext == null) {
            return;
        }
        try {
            appContext.publishEvent(event);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }
}